package com.senven.books.framework.web.model;

import com.alibaba.fastjson.annotation.JSONField;
import com.senven.books.modules.system.user.entity.SysUser;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author : longshengyi
 * @description :
 * @createDate : 2024/7/21 11:32
 */
@Data
@NoArgsConstructor
public class LoginUser implements UserDetails {

    private SysUser sysUser;

    //查询用户权限信息
    private List<String> permissions;

    public LoginUser(SysUser sysUser, List<String> permissions) {
        this.sysUser = sysUser;
        this.permissions = permissions;
    }

    @JSONField(serialize = false)
    private List<SimpleGrantedAuthority> authorities;


    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        if (authorities != null) {
            return authorities;
        }
        authorities = permissions
                .stream()
                .map(SimpleGrantedAuthority::new)
                .collect(Collectors.toList());

        //最终返回转换结果
        return authorities;
    }

    @Override
    public String getPassword() {
        return sysUser.getPassword();
    }

    @Override
    public String getUsername() {
        return sysUser.getName();
    }

    //判断登录状态是否过期。把这个改成true，表示永不过期
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    //判断账号是否被锁定。把这个改成true
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    //判断登录凭证是否过期。把这个改成true，表示永不过期
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    //判断用户是否可用。把这个改成true，表示可用状态
    @Override
    public boolean isEnabled() {
        return true;
    }
}
